package org.dromara.business.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.business.domain.OrphanDetails;
import org.dromara.business.domain.bo.OrphanDetailsBo;
import org.dromara.business.domain.vo.BusinessConfigVo;
import org.dromara.business.domain.vo.OrphanDetailsVo;
import org.dromara.business.mapper.OrphanDetailsMapper;
import org.dromara.business.service.BusinessConfigService;
import org.dromara.business.service.OrphanDetailsService;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.enums.UserStatus;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.helper.DataPermissionHelper;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.bo.SysUserBo;
import org.dromara.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 孤儿详细信息Service业务层处理
 *
 * @author zlj
 * @date 2025-01-18
 */
@RequiredArgsConstructor
@Service
public class OrphanDetailsServiceImpl extends ServiceImpl<OrphanDetailsMapper,OrphanDetails> implements OrphanDetailsService {

    private final OrphanDetailsMapper orphanDetailsMapper ;
    private final BusinessConfigService businessConfigService;
    private final ISysUserService userService;

    /**
     * 查询孤儿详细信息
     */
    @Override
    public OrphanDetailsVo queryById(Long userId){

        OrphanDetails orphanDetails = this.lambdaQuery().eq(OrphanDetails::getUserId, userId).one();
        OrphanDetailsVo vo = MapstructUtils.convert(orphanDetails, OrphanDetailsVo.class);
        translate(vo);
        return vo;
    }

    private void translate(OrphanDetailsVo vo) {
        if (null == vo){
            return ;
        }
        if (null !=vo.getSex()){

            if ("0".equals(vo.getSex())){
                vo.setSexF("男");
            }else {
                vo.setSexF("女");
            }
        }
        if (null!=vo.getIsIll()){
            if ("0".equals(vo.getIsIll())){
                vo.setIsIllF("是");
            }else {
                vo.setIsIllF("否");
            }
        }

        if (null!=vo.getIsSubsistenceAllowance()){


            if ("0".equals(vo.getIsSubsistenceAllowance())){
                vo.setIsSubsistenceAllowanceF("是");
            }else {
                vo.setIsSubsistenceAllowanceF("否");
            }
        }
        if (null!=vo.getIsPreciseHelp()){


            if ("0".equals(vo.getIsSubsistenceAllowance())){
                vo.setIsPreciseHelpF("是");
            }else {
                vo.setIsPreciseHelpF("否");
            }
        }
        if (null!=vo.getHelpNeeds()){
            vo.setHelpNeedsF(vo.getHelpNeeds().split(","));

        }

    }

    /**
     * 查询孤儿详细信息列表
     */
    @Override
    public TableDataInfo<OrphanDetailsVo> queryPageList(OrphanDetailsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OrphanDetails> lqw = buildQueryWrapper(bo);
        Page<OrphanDetailsVo> result = orphanDetailsMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询孤儿详细信息列表
     */
    @Override
    public List<OrphanDetailsVo> queryList(OrphanDetailsBo bo) {
        LambdaQueryWrapper<OrphanDetails> lqw = buildQueryWrapper(bo);
        return orphanDetailsMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OrphanDetails> buildQueryWrapper(OrphanDetailsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OrphanDetails> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getName()), OrphanDetails::getName, bo.getName());
        lqw.like(StrUtil.isNotBlank(bo.getPetName()), OrphanDetails::getPetName, bo.getPetName());
        lqw.eq(bo.getAge() != null, OrphanDetails::getAge, bo.getAge());
        lqw.eq(StrUtil.isNotBlank(bo.getIsIll()), OrphanDetails::getIsIll, bo.getIsIll());
        lqw.eq(StrUtil.isNotBlank(bo.getIsSubsistenceAllowance()), OrphanDetails::getIsSubsistenceAllowance, bo.getIsSubsistenceAllowance());
        lqw.eq(StrUtil.isNotBlank(bo.getIsPreciseHelp()), OrphanDetails::getIsPreciseHelp, bo.getIsPreciseHelp());
        lqw.orderByDesc(OrphanDetails::getCreateTime);
        return lqw;
    }

    /**
     * 新增孤儿详细信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(OrphanDetailsBo bo) {
        OrphanDetails add = MapstructUtils.convert(bo, OrphanDetails.class);
        validEntityBeforeSave(add);
        if (null==bo.getPicture()){
            if ("0".equals(bo.getSex())){
                List<BusinessConfigVo> randomPictureMaleOrphan = businessConfigService.queryByKey("random_picture_male_orphan");
                String configValue = randomPictureMaleOrphan.get(0).getConfigValue();
                add.setPicture(configValue);
            }else {
                List<BusinessConfigVo> randomPictureMaleOrphan = businessConfigService.queryByKey("random_pictures_orphan_girls");
                String configValue = randomPictureMaleOrphan.get(0).getConfigValue();
                add.setPicture(configValue);
            }
        }

        boolean flag = orphanDetailsMapper.insert(add) > 0;
        boolean update = userService.lambdaUpdate().set(SysUser::getName, bo.getName()).set(SysUser::getType,1).eq(SysUser::getUserId, bo.getUserId()).update();
        if (flag) {
            bo.setUserId(add.getUserId());
        }
        return flag;
    }

    /**
     * 修改孤儿详细信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(OrphanDetailsBo bo) {
        OrphanDetails update = MapstructUtils.convert(bo, OrphanDetails.class);
        validEntityBeforeSave(update);

        SysUser user = userService.getById(bo.getUserId());
        if ("2".equals(bo.getState())){
            user.setType("1");
        }
        user.setName( bo.getName());
        userService.updateById(user);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OrphanDetails entity){

    }

    /**
     * 批量删除孤儿详细信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){

        }
        return orphanDetailsMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public int add(OrphanDetailsBo bo) {
        // 新增用户
        Long userId= addUser(bo);
        bo.setUserId(userId);
        Boolean b = insertByBo(bo);
        return b?1:-1;
    }

    private Long addUser(OrphanDetailsBo bo) {

        SysUserBo userBo = new SysUserBo();

        userBo.setUserName(bo.getName());
        userBo.setSex(bo.getSex());



        userBo.setRoleIds(new Long[]{UserConstants.FRONT_ROLE_ID});
        userBo.setStatus(UserStatus.OK.getCode());
        userBo.setUserType(UserType.XCX_USER.getUserType());
        userBo.setNickName("用户" + RandomUtil.randomNumbers(6));
        userBo.setDeptId(Constants.TOP_PARENT_ID);
        userBo.setPostIds(new Long[]{4L});
        TenantHelper.ignore(() -> DataPermissionHelper.ignore(() -> userService.insertUser(userBo)));
        return userBo.getUserId();
    }


}
